import os
import sys
import platform
import subprocess
# 不行，用不了，以之前自己在Bilibili发的教程来做。
def escape_srt_path(path: str) -> str:
    """
    转换 Windows 路径，替换 \ 为 / 并转义方括号
    """
    path = os.path.abspath(path).replace('\\', '/')
    path = path.replace('[', r'\[').replace(']', r'\]')
    return path

def process_video(video_path: str, srt_path: str, output_path: str, font_name: str, fonts_dir: str):
    """
    使用 FFmpeg 烧录字幕
    """
    # 获取视频高度计算边距
    try:
        probe = subprocess.run([
            'ffprobe', '-v', 'error', '-select_streams', 'v:0',
            '-show_entries', 'stream=height', '-of', 'csv=p=0', video_path
        ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
        height = int(probe.stdout.strip().split('\n')[0])
        margin_v = int(height * 0.3)  # 30% 下边距
    except Exception as e:
        print(f"获取视频高度失败: {e}, 使用默认边距50")
        margin_v = 50

    srt_escaped = escape_srt_path(srt_path)

    # 构造字幕滤镜
    filter_str = (
        f"subtitles='{srt_escaped}':"
        f"force_style='FontName={font_name},FontSize=24,MarginV={margin_v},Outline=1,Shadow=0'"
    )
    if fonts_dir:
        filter_str += f":fontsdir='{fonts_dir}'"

    os.makedirs(os.path.dirname(output_path), exist_ok=True)

    cmd = [
        'ffmpeg', '-y',
        '-i', video_path,
        '-vf', filter_str,
        '-c:a', 'copy',
        '-c:v', 'libx264', '-crf', '18',
        output_path
    ]

    try:
        subprocess.run(cmd, check=True)
        print(f"{video_path} 处理完成 -> {output_path}")
    except subprocess.CalledProcessError:
        print(f"{video_path} 处理失败")

def main(video_folder: str, subtitle_folder: str, output_folder: str):
    # 设置字体
    system = platform.system()
    if system == 'Windows':
        font_name = "SimHei"  # Windows 中文字体
        fonts_dir = None
    else:
        font_name = "Noto Sans CJK SC Regular"
        fonts_dir = "/usr/share/fonts/truetype"

    # 递归遍历视频文件夹
    for root, dirs, files in os.walk(video_folder):
        for file in files:
            if not file.lower().endswith('.mp4'):
                continue

            video_path = os.path.join(root, file)
            # 构造对应字幕路径
            rel_path = os.path.relpath(video_path, video_folder)
            base_name = os.path.splitext(rel_path)[0]
            srt_path = os.path.join(subtitle_folder, base_name + ".ass")

            if not os.path.exists(srt_path):
                print(f"跳过 {video_path}，未找到匹配字幕")
                continue

            output_path = os.path.join(output_folder, rel_path)

            process_video(video_path, srt_path, output_path, font_name, fonts_dir)
main(r"C:\Users\33720\Desktop\xmly27\Funingna1.12",r"C:\Users\33720\Desktop\Srtout",r"C:\Users\33720\Desktop\SrtoutMP4")

# if __name__ == "__main__":
#     if len(sys.argv) != 4:
#         print("用法: python script.py 视频文件夹路径 字幕文件夹路径 输出文件夹路径")
#         sys.exit(1)
#     video_folder = sys.argv[1]
#     subtitle_folder = sys.argv[2]
#     output_folder = sys.argv[3]
#     main(video_folder, subtitle_folder, output_folder)
